package com.qf.mybatisplus.utils;

import com.lowagie.text.pdf.BarcodePDF417;
import com.spire.barcode.BarCodeGenerator;
import com.spire.barcode.BarCodeType;
import com.spire.barcode.BarcodeSettings;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.*;
import java.util.Base64;

/**
 * @Author ChengJiZe
 * @Date 2019/7/1
 */
public class TXMUtils {

    private static final Logger logger = LoggerFactory.getLogger(TXMUtils.class);

    /**
    *@Description 生成Code_128条形码
    *@Author ChengJiZe
    *@Date 10:25 2019/7/3
    **/
    public static String creatCode128(String path,String msg) throws IOException {
        File file = new File(path);
        if (!file.exists()) {
            file.mkdirs();
        }
//        msg = msg.getBytes("utf-8").toString();
        //创建BarcodeSettings实例
        BarcodeSettings settings = new BarcodeSettings();
        //设置条形码类型
        settings.setType(BarCodeType.Code_128);
        //设置条形码数据
        settings.setData(msg);
        //设置条形码显示数据
        settings.setData2D(msg);

        settings.setImageWidth(100);
        settings.setBarHeight(50);
        settings.setBarHeight(15);

        //显示数据
        settings.setShowText(false);
        // 设置显示的数据在条形码上面还是下面
        settings.setShowTextOnBottom(false);
        //设置边框为不可见
        settings.hasBorder(false);
        //创建BarCodeGenerator实例
        BarCodeGenerator barCodeGenerator = new BarCodeGenerator(settings);
        //根据settings生成图像数据，保存至BufferedImage实例
        BufferedImage bufferedImage = barCodeGenerator.generateImage();
        //保存为PNG图片
        ImageIO.write(bufferedImage, "png", file);
        logger.info("条形码生成成功");
        String base64 = Base64Util.imageToBase64(path);
        //删除图片
//        file.delete();
        return base64;
    }
    /**
     *@Description 生成Code_128条形码,无需生成文件
     *@Author Cola.Niu
     *@Date 2020-10-12
     **/
    public static String creatCode128(String msg) throws IOException {
        // 使用编码
//        msg = msg.getBytes("utf-8").toString();
        //创建BarcodeSettings实例
        BarcodeSettings settings = new BarcodeSettings();
        //设置条形码类型
        settings.setType(BarCodeType.Code_128);
        //设置条形码数据
        settings.setData(msg);
        //设置条形码显示数据
//        settings.setData2D(msg);
        //显示数据
        settings.setShowText(false);
        settings.setShowTextOnBottom(false);
        //设置边框为不可见
        settings.hasBorder(false);
        //创建BarCodeGenerator实例
        BarCodeGenerator barCodeGenerator = new BarCodeGenerator(settings);
        //根据settings生成图像数据，保存至BufferedImage实例
        BufferedImage bufferedImage = barCodeGenerator.generateImage();
        //转base64
        ByteArrayOutputStream stream = new ByteArrayOutputStream();
        ImageIO.write(bufferedImage, "png", stream);
        Base64.Encoder encoder = Base64.getEncoder();

        return encoder.encodeToString(stream.toByteArray());
    }

    /**
     * @Description: 根据str,font的样式输出条形码
     * @Param:
     * @return: 条形码
     * @Author: Chen
     * @Date: 2020/11/12
     */
    public static String createImage(String str, Font font, Integer width, Integer height) throws Exception {
        // 创建图片
        BufferedImage image = new BufferedImage(width, height,
                BufferedImage.TYPE_INT_BGR);
        Graphics g = image.getGraphics();
        g.setClip(0, 0, width, height);
        g.setColor(Color.white);
        // 先用白色填充整张图片,也就是背景
        g.fillRect(0, 0, width, height);
        // 在换成黑色
        g.setColor(Color.black);
        // 设置画笔字体
        g.setFont(font);
        /** 用于获得垂直居中y */
        Rectangle clip = g.getClipBounds();
        FontMetrics fm = g.getFontMetrics(font);
        int ascent = fm.getAscent();
        int descent = fm.getDescent();
        int y = (clip.height - (ascent + descent)) / 2 + ascent;
        /**获取起始x轴*/
        int strLen = fm.stringWidth(str);
        int x = (width - strLen)/2;
        g.drawString(str, x, y);
        g.dispose();
        //转base64
        ByteArrayOutputStream stream = new ByteArrayOutputStream();
        ImageIO.write(image, "png", stream);
        Base64.Encoder encoder = Base64.getEncoder();

        logger.info("条形码生成成功");
        return encoder.encodeToString(stream.toByteArray());
    }

    /**
     * 根据str,font的样式以及输出文件目录
     * @param str	字符串
     * @param font	字体
     * @param outFile	输出文件位置
     * @param width	宽度
     * @param height	高度
     * @throws Exception
     * @author MR.Zhang
     * @date 2020-11-12 9:30
     */
    public static void createImage(String str, Font font, File outFile,
                                   Integer width, Integer height) throws Exception {
        // 创建图片
        BufferedImage image = new BufferedImage(width, height,
                BufferedImage.TYPE_INT_BGR);
        Graphics g = image.getGraphics();
        g.setClip(0, 0, width, height);
        g.setColor(Color.white);
        // 先用白色填充整张图片,也就是背景
        g.fillRect(0, 0, width, height);
        // 在换成黑色
        g.setColor(Color.black);
        // 设置画笔字体
        g.setFont(font);
        /** 用于获得垂直居中y */
        Rectangle clip = g.getClipBounds();
        FontMetrics fm = g.getFontMetrics(font);
        int ascent = fm.getAscent();
        int descent = fm.getDescent();
        int y = (clip.height - (ascent + descent)) / 2 + ascent;
        /**获取起始x轴*/
        int strLen = fm.stringWidth(str);
        int x = (width - strLen)/2;

        g.drawString(str, x, y);
        g.dispose();
        // 输出png图片
        ImageIO.write(image, "png", outFile);
        logger.info("条形码生成成功");
        String base64 = Base64Util.imageToBase64(outFile.getPath());
        System.out.println("base64:" + base64);
        //删除图片
//        file.delete();
    }

    /**
     　　* @Description: 根据tff文件加载字体。
     　　* @throws
     　　* @author MR.Zhang
     　　* @date 2020-11-12 9:50
     　　*/
    public static Font loadFont(String fontFileName, float fontSize)  //第一个参数是外部字体名，第二个是字体大小
    {
        try
        {
            File file = new File(fontFileName);
            FileInputStream aixing = new FileInputStream(file);
            Font dynamicFont = Font.createFont(Font.TRUETYPE_FONT, aixing);
            Font dynamicFontPt = dynamicFont.deriveFont(fontSize);
            aixing.close();
            return dynamicFontPt;
        }
        catch(Exception e)//异常处理
        {
            e.printStackTrace();
            return new Font("宋体", Font.PLAIN, 14);
        }
    }

    /**
     * @Description:
     * @Param:
     * @return:
     * @Author: Chen
     * @Date: 2020/11/12
     */
    static void ByteToFile(byte[] bytes)throws Exception{
        ByteArrayInputStream bais = new ByteArrayInputStream(bytes);
        BufferedImage bi1 =ImageIO.read(bais);
        try {
            File file = new File("D:\\BdDeclare\\txm1\\00000000003.png");//可以是jpg,png,gif格式
            if (!file.exists()) {
                file.mkdirs();
            }
            ImageIO.write(bi1, "png", file);//不管输出什么格式图片，此处不需改动
        } catch (IOException e) {
            e.printStackTrace();
        }finally{
            bais.close();
        }
    }



    public static String creatCodePdf417(String path, String msg) throws IOException {
        File file = new File(path);
        if (!file.exists()) {
            file.mkdirs();
        }
        BarcodePDF417 pdf417 = new BarcodePDF417();
        Image barcode;
        pdf417.setText(msg);//设置文本
        pdf417.setErrorLevel(8);//设置安全等级
        pdf417.setYHeight(10F);//设置宽窄比例

        //设置放大因子
        barcode = pdf417.createAwtImage(Color.black, Color.white);
//        barcode.setAccelerationPriority(10);
        BufferedImage img = new BufferedImage((int) barcode.getWidth(null), (int) barcode.getHeight(null), BufferedImage.TYPE_INT_RGB);
        Graphics g = img.getGraphics();
        g.drawImage(barcode, 0, 0, Color.white, null);
        ImageIO.write(img, "png", file);
        logger.info("条形码生成成功");
        String base64 = Base64Util.imageToBase64(path);
        //删除图片
//        file.delete();
        return base64;
    }

    public static void main(String[] args) throws IOException {
        String path = "D:/BdDeclare/txm/" + StringUtils.getUUID() + ".png";
        String msg = "201909080024";
        String s = creatCode128(path, msg);
        System.out.println(s);
    }


}
